package com.dgut.epidemic.security;

import com.dgut.epidemic.mapper.UserMapper;
import com.dgut.epidemic.pojo.MyUserDetails;
import com.dgut.epidemic.service.CaptchaService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Author: wuhaoduan
 * Date: 2021/6/5 11:46
 */
@Service
@RequiredArgsConstructor
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Resource
    private CaptchaService captchaService;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ticket=request.getParameter("ticket");
        String randStr=request.getParameter("randStr");
        if(captchaService.verifyTicket(ticket,randStr) == -1)
            throw new BadCredentialsException("验证失败,请重新登录");
        return userMapper.findUserByName(userName)
                .map(MyUserDetails::new)
                .orElseThrow(() -> new UsernameNotFoundException("Not found: " + userName));
    }
}
